// DialerPlugin.kt
package com.sanji.audio_test

import android.app.Activity
import android.widget.Toast
import io.flutter.embedding.engine.plugins.FlutterPlugin
import io.flutter.embedding.engine.plugins.activity.ActivityAware
import io.flutter.embedding.engine.plugins.activity.ActivityPluginBinding
import io.flutter.plugin.common.MethodCall
import io.flutter.plugin.common.MethodChannel
import io.flutter.plugin.common.MethodChannel.MethodCallHandler

/**
 * 拨号器插件
 * 提供Flutter调用系统拨号功能的能力
 */
class DialerPlugin : FlutterPlugin, MethodCallHandler, ActivityAware {
    private var channel: MethodChannel? = null
    private var activity: Activity? = null

    /**
     * 当插件附加到Flutter引擎时调用
     * @param flutterPluginBinding Flutter插件绑定对象
     */
    override fun onAttachedToEngine(flutterPluginBinding: FlutterPlugin.FlutterPluginBinding) {
        channel = MethodChannel(
            flutterPluginBinding.binaryMessenger,
            "dialer"
        )
        channel?.setMethodCallHandler(this)
    }

    /**
     * 处理来自Flutter的方法调用
     * @param call 方法调用对象，包含方法名和参数
     * @param result 方法调用结果回调
     */
    override fun onMethodCall(call: MethodCall, result: MethodChannel.Result) {
        when (call.method) {
            "dial" -> {
                val phoneNumber = call.arguments as? String
                if (phoneNumber != null && activity != null) {
                    Dialer.makePhoneCall(activity!!, phoneNumber)
                    result.success(true)
                } else {
                    // 显示拨号失败的Toast提示
                    Toast.makeText(activity, "拨号失败", Toast.LENGTH_SHORT).show()
                    result.error("INVALID_NUMBER", "电话号码无效", null)
                }
            }
            else -> result.notImplemented()
        }
    }

    /**
     * 当插件从Flutter引擎分离时调用
     * @param binding Flutter插件绑定对象
     */
    override fun onDetachedFromEngine(binding: FlutterPlugin.FlutterPluginBinding) {
        channel?.setMethodCallHandler(null)
        channel = null
    }

    /**
     * 当插件附加到Activity时调用
     * @param binding Activity插件绑定对象
     */
    override fun onAttachedToActivity(binding: ActivityPluginBinding) {
        activity = binding.activity
    }

    /**
     * 当插件从Activity分离时调用
     */
    override fun onDetachedFromActivity() {
        activity = null
    }

    /**
     * 当Activity因配置更改重新附加时调用
     * @param binding Activity插件绑定对象
     */
    override fun onReattachedToActivityForConfigChanges(binding: ActivityPluginBinding) {
        onAttachedToActivity(binding)
    }

    /**
     * 当Activity因配置更改分离时调用
     */
    override fun onDetachedFromActivityForConfigChanges() {
        onDetachedFromActivity()
    }
}